package com.mzmarket.market.console.controller;

import com.mzmarket.market.console.domain.CategoryCellVO;
import com.mzmarket.market.console.domain.CategoryDetailVO;
import com.mzmarket.market.console.domain.CategoryListVO;
import com.mzmarket.market.console.domain.MessageVO;
import com.mzmarket.market.module.entity.Category;
import com.mzmarket.market.module.entity.Product;
import com.mzmarket.market.module.service.CategoryService;
import com.mzmarket.market.module.service.ProductService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@RestController
public class CategoryController {
    @Autowired
    private ProductService productService;

    @Autowired
    private CategoryService categoryService;

    @RequestMapping("/admin/category/insert")
    public MessageVO categoryInsert(@RequestParam(required = false, name = "name") String name,
                                    @RequestParam(required = false, name = "image") String image) {
        Long result = null;

        try {
            result = categoryService.edit(null, name, image);
        } catch (RuntimeException e) {
            log.warn(e.getMessage());
        }
        return result != null ? new MessageVO().setMessage("id = " + result) : new MessageVO().setMessage("Insert " +
                "failed");
    }

    @RequestMapping("/admin/category/update")
    public MessageVO categoryUpdate(@RequestParam(required = false, name = "id") Long id,
                                    @RequestParam(required = false, name = "name") String name,
                                    @RequestParam(required = false, name = "image") String image) {
        Long result = null;

        try {
            result = categoryService.edit(id, name, image);
        } catch (RuntimeException e) {
            log.warn(e.getMessage());
        }
        return result != null ? new MessageVO().setMessage("id = " + result) : new MessageVO().setMessage("Updated " +
                "failed");
    }

    @RequestMapping("/admin/category/delete")
    public MessageVO categoryDelete(@RequestParam(name = "id", required = false) Long id) {
        int result = 0;

        try {
            result = categoryService.delete(id);
        } catch (Exception e) {
            log.warn(e.getMessage());
        }

        List<Product> productList = null;
        try {
            productList = productService.getAll();
        } catch (Exception e) {
            log.warn(e.getMessage());
        }
        if (productList != null) {//将查到的列表categoryId = id的数据删除
            for (Product product : productList) {
                if (product.getCategoryId().equals(id)) {
                    try {
                        productService.delete(product.getId());
                    } catch (Exception e) {
                        log.warn(e.getMessage());
                    }
                }
            }
        }

        return result == 1 ? new MessageVO().setMessage("Deleted Successfully") : new MessageVO().setMessage("Delete " +
                "failed");
    }

    @RequestMapping("/admin/category/list")
    public CategoryListVO categoryList() {
        List<Category> categoryList = null;
        try {
            categoryList = categoryService.getCategoryList();
        } catch (Exception e) {
            log.warn(e.getMessage());
        }

        if (categoryList != null) {
            List<CategoryCellVO> categoryCellVOList = new ArrayList<>();
            for (Category category : categoryList) {
                categoryCellVOList.add(new CategoryCellVO().setName(category.getName())
                        .setId(category.getId())
                        .setImage(category.getImage()));
            }
            return new CategoryListVO().setList(categoryCellVOList);
        } else {
            return new CategoryListVO();
        }
    }

    @RequestMapping("/admin/category/detail")
    public CategoryDetailVO categoryDetail(@RequestParam(name = "id", required = false) Long id) {
        Category category = null;

        try {
            category = categoryService.getById(id);
        } catch (Exception e) {
            log.warn(e.getMessage());
        }

        if (category != null) {
            String createTime = LocalDateTime.ofInstant(
                    Instant.ofEpochSecond(category.getCreateTime()),
                    ZoneId.systemDefault()
            ).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

            String updateTime = LocalDateTime.ofInstant(
                    Instant.ofEpochSecond(category.getUpdateTime()),
                    ZoneId.systemDefault()
            ).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

            return new CategoryDetailVO()
                    .setName(category.getName())
                    .setImage(category.getImage())
                    .setCreateTime(createTime)
                    .setUpdateTime(updateTime);
        } else {
            log.warn("Category not found");
            return new CategoryDetailVO();
        }
    }
}
